﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BluSteamClient.Model.Utility;
using System.Threading;
using System.IO;
using System.Xml.Serialization;

namespace BluSteamClient.Model
{
    public class PacketReceiver
    {
        #region Fields

        private const int DIRECTIVE = 3;
        private static PacketReceiver _instance;

        public event EventHandler LoginSuccess;
        public event EventHandler RegisterSuccess;
        public event EventHandler UpdateUserList;

        #endregion

        #region Constructors

        private PacketReceiver()
        {
        }

        #endregion

        #region Properties

        public static PacketReceiver Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new PacketReceiver();
                }
                return _instance;
            }
        }

        public bool IsRunning
        {
            get;
            set;
        }

        public UsersList UserList
        {
            get;
            set;
        }

        #endregion

        #region Methods

        public void Start()
        {
            this.IsRunning = true;
            Thread receiverThread = new Thread(new ThreadStart(Receive));
            receiverThread.IsBackground = true;
            receiverThread.Start();
        }

        public void Receive()
        {
            while (IsRunning)
            {
                string packet = TcpNetwork.Receive();
                Console.WriteLine(packet);
                this.Handle(packet);
            }
        }

        public void Handle(string message)
        {
            if (message == null) return;
          
            string[] protocolStrings = message.Split('~');
            switch (protocolStrings[DIRECTIVE])
            {
                case "LOGIN_SUCCESS":
                    if (LoginSuccess != null) LoginSuccess(this, EventArgs.Empty);
                    break;

                case "REGISTER_SUCCESS":
                    if (RegisterSuccess != null) RegisterSuccess(this, EventArgs.Empty);
                    break;

                case "UPDATE_USERLIST":
                    if (this.UserList != null) 
                        this.UserList.SetUserList(protocolStrings[4]);

                    if (UpdateUserList != null) UpdateUserList(this, EventArgs.Empty);
                    break;
            }
        }

        public void Stop()
        {
            this.IsRunning = false;
        }

        #endregion
    }
}
